package com.ansion.basedb.dao.model;

import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.ansion.log.VLog;
import com.ansion.utils.BotPreferenceUtils;
import com.ansion.utils.ContactUtil;
import com.ansion.utils.GsonUtil;
import com.ansion.utils.ServerTime;

import org.json.JSONException;
import org.json.JSONObject;

//该对象JSON序列化后存储到配置文件里，下次启动程序时自动进行Connect
public class CurrentUser extends UserModel {
    //头像是否上传成功
    private boolean isAvatarUpdated = true;

    //除头像的其他需要异步上传的用户信息是否上传成功：现在只包括 note
    private boolean isOtherDataUpdated = true;

    // 登录账户
    private String loginId;
    // 自动登录的密码
    private String loginToken;

    private String loginAccount;

    private String loginTokenMemory;

    private int lastDevType;
    private String lastDevKey;

    private String webloginkey;  //用于网页登陆

    private boolean webHasLogin = false;

    private boolean receivePushWhenWeblogin = true;

    private String deviceId;

    /**
     * CurrentUser在每次更新用户信息的时候都会重新new一份.
     * 为了防止UserProfileExtraModel每次都反序列化所以设置为static
     */
    private static UserProfileExtraModel userProfileExtraModel;
    /**
     * 服务端返回的时间
     */
    private long updated;

    /**
     * 用于异步同步profile数据
     */
    private long ohterdataUpdated;
    /**
     * 用于异步同步avatar数据时间 毫秒
     */
    private long avatarUpdated;
    private String sessionTag;// 每次登陆换一个SessionTag,用于解决切换账户问题
    private long created;
    private boolean isMessageLoadingFinish;//消息是否推送完成
    private String cliip;
    private String regionCode = "";
    //桌面端扫码登录加的内存字段
    private String webLoginDeviceKey;
    private String webClientVersion;

    private boolean showLandingPage;//0:not show, 1:show


    public void setWebHasLogin(boolean webHasLogin) {
        this.webHasLogin = webHasLogin;
        ContactUtil.setWebLogin(webHasLogin);
        if (webHasLogin) {  //网页登录的时候立马将receivepush设为false, 正常应该存储在服务端，然后获取对应的值
            receivePushWhenWeblogin = true;
        }
    }

    public boolean isWebHasLogin() {
        return webHasLogin;
    }

    public boolean isReceivePushWhenWeblogin() {
        return receivePushWhenWeblogin;
    }

    public void setReceivePushWhenWeblogin(boolean receive) {
        receivePushWhenWeblogin = receive;
    }

    public void setWebloginkey(String key) {
        webloginkey = key;
    }

    public String getWebloginkey() {
        return webloginkey;
    }


    public void setWebLoginDeviceKey(String webLoginDeviceKey) {
        this.webLoginDeviceKey = webLoginDeviceKey;
    }

    public String getWebLoginDeviceKey() {
        return webLoginDeviceKey;
    }


    public void setWebClientVersion(String webClientVersion) {
        this.webClientVersion = webClientVersion;
    }

    public String getWebClientVersion() {
        return webClientVersion;
    }


    public String getRegionCode() {
        return regionCode;
    }

    public void setRegionCode(String regioncode) {
        this.regionCode = regioncode;
    }

    public String getCliip() {
        return cliip;
    }

    public void setCliip(String cliip) {
        this.cliip = cliip;
    }

    public String getSessionTag() {
        return sessionTag;
    }

    public void setSessionTag(String sessionTag) {
        this.sessionTag = sessionTag;
    }

    public String getLoginId() {
        return loginId;
    }

    public void setLoginId(String loginId) {
        this.loginId = loginId;
    }

    public String getLoginToken() {
        return loginToken;
    }

    public void setLoginToken(String loginToken) {
        this.loginToken = loginToken;
    }

    public String getLoginAccount() {
        return loginAccount;
    }

    public void setLoginAccount(String loginAccount) {
        this.loginAccount = loginAccount;
    }

    public String getLoginTokenMemory() {
        return loginTokenMemory;
    }

    public void setLoginTokenMemory(String loginTokenMemory) {
        this.loginTokenMemory = loginTokenMemory;
    }

    public long getUpdated() {
        return updated;
    }

    public void setUpdated(long updated) {
        this.updated = updated;
    }


    public boolean isAvatarUpdated() {
        return isAvatarUpdated;
    }

    public void setAvatarUpdated(boolean isAvatarUpdated) {
        this.isAvatarUpdated = isAvatarUpdated;
    }

    public boolean isOtherDataUpdated() {
        return isOtherDataUpdated;
    }

    public void setOtherDataUpdated(boolean isOtherDataUpdated) {
        this.isOtherDataUpdated = isOtherDataUpdated;
    }

    public long getAvatarUpdated() {
        return avatarUpdated;
    }

    public void setAvatarUpdatedTime(long avatarUpdated) {
        this.avatarUpdated = avatarUpdated;
        this.isAvatarUpdated = false;
    }


    public long getOhterdataUpdated() {
        return ohterdataUpdated;
    }

    public void setOhterdataUpdatedTime(long ohterdataUpdated) {
        this.ohterdataUpdated = ohterdataUpdated;
        this.isOtherDataUpdated = false;
    }


    public void setMessageLoadingFinish(boolean isMessageLoadingFinish) {
        this.isMessageLoadingFinish = isMessageLoadingFinish;
    }

    public long getCreated() {
        return created;
    }

    public void setCreated(long created) {
        this.created = created;
    }


    public int getLastDevType() {
        return lastDevType;
    }

    public void setLastDevType(int lastDevType) {
        this.lastDevType = lastDevType;
    }

    public String getLastDevKey() {
        return lastDevKey;
    }

    public void setLastDevKey(String lastDevKey) {
        this.lastDevKey = lastDevKey;
    }

    @Override
    public String toString() {
        return "CurrentUser{" +
                "isAvatarUpdated=" + isAvatarUpdated +
                ", isOtherDataUpdated=" + isOtherDataUpdated +
                ", loginId='" + loginId + '\'' +
                ", loginToken='" + loginToken + '\'' +
                ", loginAccount='" + loginAccount + '\'' +
                ", loginTokenMemory='" + loginTokenMemory + '\'' +
                ", lastDevType=" + lastDevType +
                ", lastDevKey='" + lastDevKey + '\'' +
                ", updated=" + updated +
                ", ohterdataUpdated=" + ohterdataUpdated +
                ", avatarUpdated=" + avatarUpdated +
                ", sessionTag='" + sessionTag + '\'' +
                ", created=" + created +
                ", isMessageLoadingFinish=" + isMessageLoadingFinish +
                ", cliip='" + cliip + '\'' +
                ", regionCode='" + regionCode + '\'' +
                '}';
    }

    public void setPasswordset(boolean b) {
        // TODO Auto-generated method stub

    }

    public boolean isPhoneAuth() {
        // TODO Auto-generated method stub
        return true;
    }


    @Override
    public CurrentUser clone() {
        CurrentUser o = null;
        try {
            o = (CurrentUser) super.clone();
        } catch (Exception e) {
            VLog.e("TAG_LOG_ERROR", e);
        }
        return o;
    }

    public boolean isRealVip() {
        return super.isVip() && getVipExpireDate() > ServerTime.getServerTimeMillisecond();
    }

    public boolean isRealBadgeWallet() {
        return super.isBadgeWallet() && getWalletExpireTime() > ServerTime.getServerTimeMillisecond();
    }

    public void destroy() {
        userProfileExtraModel = null;
        BotPreferenceUtils.getInstance().setUserProfileExtraInfo("");
    }

    @Nullable
    public UserProfileExtraModel getUserExtraInfo() {
        // 因为userProfileExtraModel是个单例, 防止因切账号导致没有释放的情况
        if (userProfileExtraModel != null) {
            if (getUserId() != userProfileExtraModel.uid) {
                userProfileExtraModel = null;
            }
        }

        //不为空的话直接用内存中的数据
        if (userProfileExtraModel != null) return userProfileExtraModel;
        if (BotPreferenceUtils.getInstance() == null) return userProfileExtraModel;
        String userProfileExtraInfo = BotPreferenceUtils.getInstance().getUserProfileExtraInfo();
        if (TextUtils.isEmpty(userProfileExtraInfo)) return null;
        userProfileExtraModel = GsonUtil.fromJson(userProfileExtraInfo, UserProfileExtraModel.class);
        return userProfileExtraModel;
    }

    public String getDeviceId() {
        return deviceId;
    }

    public void setDeviceId(String deviceId) {
        this.deviceId = deviceId;
    }


    public String toJsonString() {
        JSONObject jsonObject = new JSONObject();
        try {
            //UserModel属性，20个
            jsonObject.put("userId", getUserId());
            jsonObject.put("ucid", getUcid());
            jsonObject.put("oaid", getOaid());
            jsonObject.put("alias", getAlias());
            jsonObject.put("nickName", getNickName());
            jsonObject.put("avatarUrl", getAvatarUrl());
            jsonObject.put("countryCode", getCountry());
            jsonObject.put("countryPhone", getCountryPhone());
            jsonObject.put("avatarPrevUrl", getAvatarPrevUrl());
            jsonObject.put("note", getNote());
            jsonObject.put("updateTime", getUpdateTime());
            jsonObject.put("background", getBackground());
            jsonObject.put("status", getStatus());
            jsonObject.put("status_type", getStatus_type());
            jsonObject.put("isVip", isVip());
            jsonObject.put("vipExpireDate", getVipExpireDate());
            jsonObject.put("isStranger", isStranger());
            jsonObject.put("oaVerified", isOaVerified());
            jsonObject.put("oaIcon", getOaIcon());
            jsonObject.put("oaSubType", getOaSubType());
            jsonObject.put("email", getEmail());
            //新加的extraData
            encodeExtraData();
            jsonObject.put("extraData", getExtraData());

            //CurrentUser属性，22个
            jsonObject.put("isAvatarUpdated", isAvatarUpdated);
            jsonObject.put("isOtherDataUpdated", isOtherDataUpdated);
            jsonObject.put("loginId", loginId);
            jsonObject.put("loginToken", loginToken);
            jsonObject.put("loginAccount", loginAccount);
            jsonObject.put("loginTokenMemory", loginTokenMemory);
            jsonObject.put("lastDevType", lastDevType);
            jsonObject.put("lastDevKey", lastDevKey);
            jsonObject.put("webloginkey", webloginkey);
            jsonObject.put("webHasLogin", webHasLogin);
            jsonObject.put("receivePushWhenWeblogin", receivePushWhenWeblogin);
            jsonObject.put("deviceId", deviceId);
            jsonObject.put("updated", updated);
            jsonObject.put("ohterdataUpdated", ohterdataUpdated);
            jsonObject.put("avatarUpdated", avatarUpdated);
            jsonObject.put("sessionTag", sessionTag);
            jsonObject.put("created", created);
            jsonObject.put("isMessageLoadingFinish", isMessageLoadingFinish);
            jsonObject.put("cliip", cliip);
            jsonObject.put("regionCode", regionCode);
            jsonObject.put("webLoginDeviceKey", webLoginDeviceKey);
            jsonObject.put("webClientVersion", webClientVersion);

            jsonObject.put("showLandingPage", showLandingPage);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }


    public static CurrentUser fromJsonString(String jsonString) {
        CurrentUser user = new CurrentUser();
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            //User属性20个
            user.setUserId(jsonObject.optLong("userId"));
            user.setUcid(jsonObject.optString("ucid"));
            user.setOaid(jsonObject.optString("oaid"));
            user.setAlias(jsonObject.optString("alias"));
            user.setNickName(jsonObject.optString("nickName"));
            user.setAvatarUrl(jsonObject.optString("avatarUrl"));
            user.setCountry(jsonObject.optString("countryCode"));
            user.setCountryPhone(jsonObject.optString("countryPhone"));
            user.setAvatarPrevUrl(jsonObject.optString("avatarPrevUrl"));
            user.setNote(jsonObject.optString("note"));
            user.setUpdateTime(jsonObject.optLong("updateTime"));
            user.setBackground(jsonObject.optString("background"));
            user.setStatus(jsonObject.optInt("status"));
            user.setStatus_type(jsonObject.optInt("status_type"));
            user.setVip(jsonObject.optBoolean("isVip"));
            user.setVipExpireDate(jsonObject.optLong("vipExpireDate"));
            user.setStranger(jsonObject.optBoolean("isStranger"));
            user.setOaVerified(jsonObject.optBoolean("oaVerified"));
            user.setOaIcon(jsonObject.optString("oaIcon"));
            user.setOaSubType(jsonObject.optInt("oaSubType"));
            user.setEmail(jsonObject.optString("email"));
            //新加的extraData
            user.setExtraData(jsonObject.optString("extraData"));
            user.decodeExtraData();
            //CurrentUser属性，22个
            user.setAvatarUpdated(jsonObject.optBoolean("isAvatarUpdated"));
            user.setOtherDataUpdated(jsonObject.optBoolean("isOtherDataUpdated"));
            user.setLoginId(jsonObject.optString("loginId"));
            user.setLoginToken(jsonObject.optString("loginToken"));
            user.setLoginAccount(jsonObject.optString("loginAccount"));
            user.setLoginTokenMemory(jsonObject.optString("loginTokenMemory"));
            user.setLastDevType(jsonObject.optInt("lastDevType"));
            user.setLastDevKey(jsonObject.optString("lastDevKey"));
            user.setWebloginkey(jsonObject.optString("webloginkey"));
            user.setWebHasLogin(jsonObject.optBoolean("webHasLogin"));
            user.setReceivePushWhenWeblogin(jsonObject.optBoolean("receivePushWhenWeblogin"));
            user.setDeviceId(jsonObject.optString("deviceId"));
            user.setUpdated(jsonObject.optLong("updated"));
            user.setOtherDataUpdated(jsonObject.optBoolean("ohterdataUpdated"));
            user.setAvatarUpdated(jsonObject.optBoolean("avatarUpdated"));
            user.setSessionTag(jsonObject.optString("sessionTag"));
            user.setCreated(jsonObject.optLong("created"));
            user.setMessageLoadingFinish(jsonObject.optBoolean("isMessageLoadingFinish"));
            user.setCliip(jsonObject.optString("cliip"));
            user.setRegionCode(jsonObject.optString("regionCode"));
            user.setWebLoginDeviceKey(jsonObject.optString("webLoginDeviceKey"));
            user.setWebClientVersion(jsonObject.optString("webClientVersion"));
            user.setShowLandingPage(jsonObject.optBoolean("showLandingPage"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return user;
    }

    public void setShowLandingPage(boolean showLandingPage) {
        this.showLandingPage = showLandingPage;
    }

    public boolean getShowLandingPage() {
        return showLandingPage;
    }
}
